using Microsoft.EntityFrameworkCore;
using RiceShop.Models;

namespace RiceShop.Services
{
    public interface ICategoryService
    {
        Task<List<Category>> GetCategoriesAsync();
        Task<List<Category>> GetTopCategoriesAsync();
        Task<Category> GetCategoryByIdAsync(long id);
        Task<Category> CreateCategoryAsync(Category category);
        Task<Category> UpdateCategoryAsync(long id, Category category);
        Task DeleteCategoryAsync(long id);
    }

    public class CategoryService : ICategoryService
    {
        private readonly ApplicationDbContext _context;

        public CategoryService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有商品分类列表
        /// </summary>
        /// <returns>分类列表</returns>
        public async Task<List<Category>> GetCategoriesAsync()
        {
            try
            {
                // 过滤掉已删除的分类
                return await _context.Categories
                .Where(c => !c.IsDeleted)
                .OrderBy(c => c.Sort)  // 按照排序字段升序排列
                .ToListAsync() ?? new List<Category>();  // 如果结果为null，返回空列表
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return new List<Category>();  // 发生异常时返回空列表而不是null
            }
        }

        /// <summary>
        /// 获取顶级分类列表
        /// </summary>
        /// <returns>顶级分类列表</returns>
        public async Task<List<Category>> GetTopCategoriesAsync()
        {
            return await _context.Categories
                .Where(c => !c.IsDeleted && c.ParentId == 0)
                .OrderBy(c => c.Sort)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取指定分类
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <returns>分类信息</returns>
        public async Task<Category> GetCategoryByIdAsync(long id)
        {
            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.Id == id);

            if (category == null)
            {
                throw new KeyNotFoundException("分类不存在");
            }

            return category;
        }

        /// <summary>
        /// 创建新的商品分类
        /// </summary>
        /// <param name="category">分类信息</param>
        /// <returns>创建后的分类</returns>
        public async Task<Category> CreateCategoryAsync(Category category)
        {
            // 如果没有设置排序号，则设置为最大排序号+1
            if (category.Sort == 0)
            {
                var maxSort = await _context.Categories
                    .MaxAsync(c => (int?)c.Sort) ?? 0;
                category.Sort = maxSort + 1;
            }

            category.CreateTime = DateTime.Now;
            category.UpdateTime = DateTime.Now;
            category.IsDeleted = false;

            _context.Categories.Add(category);
            await _context.SaveChangesAsync();
            return category;
        }

        /// <summary>
        /// 更新商品分类信息
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <param name="categoryUpdate">更新的分类信息</param>
        /// <returns>更新后的分类</returns>
        public async Task<Category> UpdateCategoryAsync(long id, Category categoryUpdate)
        {
            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.Id == id);

            if (category == null)
            {
                throw new KeyNotFoundException("分类不存在");
            }

            // 更新分类信息
            category.Name = categoryUpdate.Name;
            category.Icon = categoryUpdate.Icon;
            category.Sort = categoryUpdate.Sort;
            category.ParentId = categoryUpdate.ParentId;
            category.Level = categoryUpdate.Level;

            await _context.SaveChangesAsync();
            return category;
        }

        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="id">分类ID</param>
        public async Task DeleteCategoryAsync(long id)
        {
            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.Id == id);

            if (category == null)
            {
                throw new KeyNotFoundException("分类不存在");
            }

            // 检查分类下是否有商品
            var hasProducts = await _context.Goods
                .AnyAsync(g => g.CateId == id);

            if (hasProducts)
            {
                throw new InvalidOperationException("该分类下存在商品，无法删除");
            }

            _context.Categories.Remove(category);
            await _context.SaveChangesAsync();
        }
    }
}